<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import Footer from "#/components/common/footer.vue"
import UserLayout from '#/components/common/user-layout.vue';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { Volume2 } from '@vben/icons';
import { getPublishedSysAnnListApi } from '#/api/lesson';
import AnnouncementDialog from '#/views/personal/modules/announcement-dialog.vue';

defineOptions({ name: 'Home' });
const certResultPath = '/lesson/certResult';
const homePath = '/lesson/home';
const route = useRoute();
const isHome = computed(() => route.path === homePath);
const isCertResultPath = computed(() => route.path === certResultPath);

// 根据当前路由生成面包屑

const breadcrumbs = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title);

  // 特殊处理证书查询结果页面
  if (isCertResultPath.value) {
    return [
      { name: '证书查询', path: '/auth/certVerify', isShow: true },
      { name: '查询结果', path: '/lesson/certResult', isShow: true },
    ];
  }

  // 使用路由匹配信息生成面包屑，处理动态参数
  const breadcrumbList = matched.map(item => {
    // 处理动态参数路由
    let path = item.path;

    // 如果路径包含动态参数（如 :id），需要替换为实际值
    if (path.includes(':')) {
      // 从当前路由参数中获取值来替换动态参数
      const params = route.params;
      path = path.replace(/:\w+/g, (match) => {
        const paramName = match.slice(1); // 去掉冒号
        const paramValue = params[paramName];
        // 确保返回字符串类型
        return Array.isArray(paramValue) ? paramValue[0] || match : paramValue || match;
      });
    }

    // 处理查询参数
    if (Object.keys(route.query).length > 0) {
      const queryString = new URLSearchParams(route.query as Record<string, string>).toString();
      if (queryString) {
        path += `?${queryString}`;
      }
    }

    if (item.meta?.hideInBreadcrumb) {
      return null;
    }

    return {
      name: item.meta?.title,
      path: path
    };
  }).filter(item => item !== null);

  return breadcrumbList;
});

// 公告相关状态（与 basic.vue 保持一致）
const sysAnnList = ref<any[]>([]);
const currentAnnIndex = ref(0);
const showBanner = ref(true);

const currentAnn = computed(() => sysAnnList.value[currentAnnIndex.value] || null);
const isLastAnn = computed(() => currentAnnIndex.value === sysAnnList.value.length - 1);
const hasAnnouncements = computed(() => sysAnnList.value.length > 0);

const dialogVisible = ref(false);
const dialogCurrentIndex = ref(0);

const handleNext = () => {
  if (isLastAnn.value) {
    showBanner.value = false;
  } else {
    currentAnnIndex.value++;
  }
};

const handleAnnouncementClick = () => {
  if (hasAnnouncements.value) {
    dialogCurrentIndex.value = currentAnnIndex.value;
    dialogVisible.value = true;
  }
};

const handleDialogClose = () => {
  dialogVisible.value = false;
};

const getPublishedSysAnnList = async () => {
  const res = await getPublishedSysAnnListApi({ type: 'upgrade' });
  sysAnnList.value = res.data;
};

onMounted(() => {
  getPublishedSysAnnList();
});

</script>
<template>
  <div class="flex h-full flex-col relative">
    <UserLayout></UserLayout>
    <div class="relative">
      <el-breadcrumb separator="/" class="bg-[#f4f5f5] pb-[12px] pl-[32px] pt-[12px] text-[12px] leading-[20px]"
        v-if="!isHome && breadcrumbs.length > 0">
        <template v-for="(bread, index) in breadcrumbs" :key="`${bread.path}-${index}`">
          <el-breadcrumb-item :to="{ path: bread.path }" :class="{ 'is-last': index === breadcrumbs.length - 1 }">
            {{ bread.name }}
          </el-breadcrumb-item>
        </template>
      </el-breadcrumb>
      <!-- 公告条幅 -->
      <div v-if="showBanner && hasAnnouncements && currentAnn"
        class="absolute top-0 left-0 bg-[#CCE1F6] w-full h-[44px] flex items-center justify-between px-[32px] py-[10px]">
        <!-- 公告图标 -->
        <div class="flex items-center flex-1">
          <VbenIcon :icon="Volume2" class="w-[20px] h-[20px] text-[#0067D1] fill-transparent" />
          <!-- 公告内容 -->
          <div class="text-[#333] text-sm flex-1 truncate mr-4 ml-[16px] cursor-pointer hover:text-[#0067D1]"
            @click="handleAnnouncementClick">
            重要公告：{{ currentAnn.title }}
          </div>
        </div>
        <!-- 下一条/关闭按钮 -->
        <button @click="handleNext"
          class="text-[#1890ff] text-sm hover:text-[#40a9ff] cursor-pointer flex-shrink-0 px-2 py-1 rounded hover:bg-white/50 transition-colors">
          {{ isLastAnn ? '关闭' : '下一条' }}
        </button>
      </div>
    </div>
    <RouterView class="flex-1 bg-[#f4f5f5] pb-[24px] px-[24px]" v-slot="{ Component }">
      <component :is="Component"></component>
    </RouterView>
    <Footer></Footer>

    <!-- 公告详情弹窗 -->
    <AnnouncementDialog v-model="dialogVisible" v-model:current-index="dialogCurrentIndex" :announcements="sysAnnList"
      title="公告详情" @close="handleDialogClose" />
  </div>
</template>
<style lang="less" scoped>
:deep(.el-breadcrumb) {
  .el-breadcrumb__item {
    .el-breadcrumb__inner.is-link {
      color: #909399;
      font-weight: normal;
    }

    &.is-last {
      .el-breadcrumb__inner.is-link {
        color: #191919;
        font-weight: 500;
      }
    }
  }
}
</style>
